﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
    Transform lastPlatform;//最后一个平台的transform，用于计算下一个平台的生成位置
    Camera mainCamera;
    float maxDistance;//平台间的最大距离
    PlayerController pControlloer;
    GameObject startButton;
    GameObject gameOverWin;
    void Start()
    {
        lastPlatform = GameObject.Find("StartPlatform").transform;
        pControlloer = Transform.FindObjectOfType<PlayerController>();
        maxDistance = pControlloer.stickMaxScale - 1.0f;//warning:平台最大间距要小于stick的最大长度
        mainCamera = Camera.main;

        startButton = Transform.FindObjectOfType<Button>().gameObject;
        gameOverWin = GameObject.Find("Canvas/GameOverDialog");
        gameOverWin.SetActive(false);
    }

    void Update()
    {
        //无限生成平台
        float halfWidth = lastPlatform.localScale.x * 0.5f;
        while (lastPlatform.position.x - halfWidth < mainCamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x)
        {
            var prefab = Resources.Load("Prefabs/Ground") as GameObject;
            prefab.transform.localScale = new Vector3(Random.Range(1, 5), 10, 1);
            float posX = lastPlatform.position.x + halfWidth + Random.Range(3, maxDistance - prefab.transform.localScale.x);
            lastPlatform = (Instantiate(prefab, new Vector3(posX, 0, 0), prefab.transform.rotation) as GameObject).transform;
        }
    }

    void OnTriggerExit2D(Collider2D col)
    {
        if (col.gameObject.tag == "Player")
        {
            //Debug.Log("Game Over!");
            StartCoroutine(GameOver(2.0f));
        }

        Destroy(col.gameObject);
    }

    IEnumerator GameOver(float waitTime)
    {
        gameOverWin.SetActive(true);
        yield return new WaitForSeconds(waitTime);
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
    //Start Button Call Back
    public void OnStartButtonClick()
    {
        pControlloer.isStartGame = true;
        startButton.SetActive(false);
    }
}
